import {
  OnGatewayConnection,
  OnGatewayInit,
  SubscribeMessage,
  WebSocketGateway,
  OnGatewayDisconnect,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { Logger } from '@nestjs/common';
import { Cube } from './types';

@WebSocketGateway({
  path: '/socket',
  allowEIO3: true,
  cors: {
    origin: /.*/,
    credentials: true,
  },
})
export class AppGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
  @WebSocketServer() private ws: Server; // socket实例
  private cubesForge: Cube[];

  afterInit() {}

  handleConnection(client: Socket) {}

  handleDisconnect(client: Socket) {}

  sendOutAllCubes() {
    this.ws.emit('resetCubes', { cubes: this.cubesForge });
  }

  @SubscribeMessage('2serverCubes')
  handleData(client: Socket, data: Cube[]): void {
    console.log(client.id, data.length, new Date().toDateString());
    this.cubesForge = data;
    try {
      this.sendOutAllCubes();
    } catch (err) {}
  }
  @SubscribeMessage('interval2serverCubes')
  handleDataInterval(client: Socket, data: Cube[]): void {
    console.log(client.id, data.length, new Date().toLocaleTimeString());
    /*this.users[client.id] = data;*/
    this.cubesForge = data;
  }
}
